import {
    validate,
    Length,
    IsNumberString
} from 'class-validator'

import { isError } from 'lodash'
import { BigNumber } from 'bignumber.js'

import { Wallet } from '@app/wallet'
import { logger } from '@pkg/logger'
import { nothrow } from '@pkg/promise'
import * as utils from '@app/methods/utils'

class Request {
    @Length(3, 8)
    symbol: string = ''

    @Length(34, 34)
    from: string = ''

    @Length(34, 34)
    to: string = ''

    @IsNumberString()
    amount: string = '0'
}

/**
 * 从指定钱包地址转移TRC20代币
 */
export async function transferTokenFrom(wallet: Wallet, params: any, callback: any) {
    const model = utils.makeModel(new Request, params)
    const errors = await validate(model)
    if (errors.length > 0) {
        callback(utils.BadRequest2(errors), undefined)
        return
    }

    const amount = new BigNumber(model.amount)
    if (amount.comparedTo(new BigNumber(0)) <= 0) {
        callback(utils.BadRequest('amount must be a positive number'), undefined)
        return
    }
 
    const receipt = await nothrow(wallet.transferTokenFrom(
        model.symbol, model.from, model.to, new BigNumber(model.amount)))
    if (isError(receipt)) {
        logger.warn('[JSON-RPC] transfer TRC20 token failed, from: %s, to: %s, amount: %s, %s',
            model.from, model.to, model.amount, receipt)
        callback({code: -32603, message: receipt.message}, undefined)
        return
    }
    logger.warn('[JSON-RPC] transfer TRC20 token successful, from: %s, to: %s, amount: %s, hash: %s',
        model.from, model.to, model.amount, receipt.txid)
    callback(undefined, receipt.txid)
}
